<?php namespace Core\Myapp\Helper\Admin;

class Navigation extends \Core\Myapp\Zobero
{
    protected $_items = array();
    public function addItem($route, $controller, $action, $title, $parent = '', $sortOrder = null, $link = true)
    {
        $id = $route;
        if($controller)
            $id .= '_' . $controller;
        if($action)
            $id .= '_' . $action;
        $url = 'javascript:void(0);';
        if($link == true)
            $url = $this->getCoreHelper('\Url')->buildUrl($route, $controller, $action);
        $this->_items[] = array(
            'id'        =>$id,
            'route'     =>$route,
            'controller'=>$controller,
            'action'    =>$action,
            'title'     =>$title,
            'parent'    =>$parent,
            'sortOrder' =>$sortOrder,
            'url'      =>$url
        );
        return $this;
    }
    public function init()
    {
        $this->_beforeInit();
        return $this->_items;
    }
    public function getHtmlSubMenu($id)
    {
        $html = '';
        if(count($this->getChildrens($id))) {
            $html .= '<ul>';
            foreach($this->getChildrens($id) as $value) {
                $html .= "<li id='".$value['id']."'><a href='".$value['url']."'>".$value['title']."</a>".$this->getHtmlSubMenu($value['id'])."</li>";
            }
            $html .= '</ul>';
        }
        return $html;
    }
    public function getChildrens($id)
    {
        $child = array();
        foreach($this->_items as $item) {
            if($item['parent']==$id)
                $child[] = $item;
        }
        usort($child, array($this, "sortHelper"));
        return $child;
    }
    protected function _beforeInit()
    {
        $this->getEventManager()->fire('admin_all_navigation_before_load', array($this));
    }

    public function getRootItems()
    {
        $rootItems = array();
        foreach($this->_items as $item) {
            if($item['parent']=='')
                $rootItems[] = $item;
        }
        usort($rootItems, array($this, "sortHelper"));
        return $rootItems;
    }
    protected function sortHelper($a, $b)
    {
        $aOrder = (int)$a['sortOrder'];
        $bOrder = (int)$b['sortOrder'];
        if ($aOrder == $bOrder) {
            return 0;
        }
        return ($aOrder < $bOrder) ? -1 : 1;
    }
}